package com.huang.viewpage;

import android.graphics.Color;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import com.clovsoft.banner.ViewPagerAdapter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity2 extends AppCompatActivity {
    private ViewPager2 viewPager2;
    private List<Fragment> mFragments = new ArrayList<>();
    private ViewPagerAdapter adapter;
    private DotIndicator[] dotIndicators;
    private int currentIndex = 0; // 当前选中的索引

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        viewPager2 = findViewById(R.id.view_pager);
        dotIndicators = new DotIndicator[]{
                findViewById(R.id.dot1),
                findViewById(R.id.dot2),
                findViewById(R.id.dot3)
        };
        initFragments();

        // 设置适配器
        adapter = new ViewPagerAdapter(getSupportFragmentManager(),this.getLifecycle(),mFragments);
        viewPager2.setAdapter(adapter);

        // 监听页面变化
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                updateDots(position); // 更新小圆点状态
            }
        });

        for (DotIndicator dotIndicator : dotIndicators) {
            dotIndicator
                    .setSelectedColor(Color.parseColor("#000000"), Color.parseColor("#fffd00"))
                    .setIndicatorWidth(30f)
                    .setIndicatorHeight(4f)
                    .requestLayout();
        }
        // 初始化状态

        viewPager2.setCurrentItem(1);
    }

    private void initFragments() {
        mFragments.add(new FirstFragment());
        mFragments.add(new SecondFragment());
        mFragments.add(new ThirdFragment());
    }

    private void updateDots(int index) {
        if (index < 0 || index >= dotIndicators.length) return;
        for (int i = 0; i < dotIndicators.length; i++) {
            dotIndicators[i].setSelected(i == index);
        }
    }
    // 调用这个方法以更新索引
    public void onTabSelected(int index) {
        currentIndex = index;
        updateDots(currentIndex);
    }

}